package com.wsd.smartcarwasher.service;

import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.dao.CouponDao;
import com.wsd.smartcarwasher.dao.StoreMapper;
import com.wsd.smartcarwasher.dao.UserCouponDao;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.CouponUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.*;

@Service
@Lazy
public class CouponService {
    private static final Logger logger = LoggerFactory.getLogger(CouponService.class);

    @Resource
    private CouponDao couponDao;
    @Resource
    private UserCouponService  userCouponService;

    @Resource
    private UserCouponDao userCouponDao;
    @Resource
    private SysDicService sysDicService;
    @Resource
    private WxService wxService;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    @Lazy
    private MachineService machineService;

    @Transactional
    public int addCoupon(Coupon coupon) {
        //coupon.setStatus(Global.COUPON_STATUS_NORMAL);
        //coupon.setCouponCode(RandomUtils.generateUpperString(10));
        coupon.setTime(new Date());
        int changeRows=couponDao.addCoupon(coupon);

        if(changeRows>0){
            this.generateWxCode(coupon);
        }

        return changeRows;
    }

    public Coupon getCouponByCouponId(int couponId) {
        return couponDao.getCouponByCouponId(couponId);
    }

    public int deleteCoupon(int couponId) {
        return couponDao.deleteCoupon(couponId);
    }

    public List<Coupon> queryAllCoupons(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Coupon> coupons = couponDao.queryAllCoupons();
        if (coupons == null) {
            return Collections.emptyList();
        }
        return coupons;
    }
    public List<Coupon> queryStoreCoupons(int partnerId) {
        List<Coupon> coupons = couponDao.queryStoreCoupons(partnerId);
        if (coupons == null) {
            return Collections.emptyList();
        }
        return coupons;
    }

    public Coupon getCouponsByCode(String couponCode) {
        return couponDao.getCouponsByCode(couponCode);
    }

    public Coupon getCouponByMachine(Integer machineId){return couponDao.getCouponByMachine(machineId);}

    public List<Coupon> getCouponByPartnerId(Integer partnerId){

       List<Coupon> couponList= couponDao.getCouponByPartnerId(partnerId);

       for (int i = 0; i <couponList.size() ; i++) {

            String storeId=couponList.get(i).getStoreId();
            if(storeId!=null&&storeId.length()>0){
                storeId = storeId.substring(0, storeId.length() -1);
            }
            List<String> storeList = Arrays.asList(storeId.split(","));

            for(String s:storeList)
            {
                if(!s.equals(""))
                {
                    StoreExample storeExample = new StoreExample();
                    storeExample.createCriteria().andIdEqualTo(Integer.parseInt(s));
                    if(couponList.get(i).getStoreName()==null)
                    {
                        couponList.get(i).setStoreName(this.storeMapper.selectByExample(storeExample).get(0).getName());

                    }else
                    {
                        couponList.get(i).setStoreName(couponList.get(i).getStoreName()+","+this.storeMapper.selectByExample(storeExample).get(0).getName());

                    }

                }
            }



        }


        return couponList;

    }

    public Coupon getCouponOneByPartnerId(Coupon coupon){
            List<String> machineId = Arrays.asList(coupon.getAvailableMachines().split(","));
            for(String s:machineId)
            {
                if(!s.equals(""))
                {
                    Machine machine=this.machineService.queryMachineById(Integer.parseInt(s));
                    if(coupon.getMachineName()==null)
                    {
                        coupon.setMachineName(machine.getName());
                    }else{
                        coupon.setMachineName(coupon.getMachineName()+","+machine.getName());
                    }
                }
            }
        return coupon;

    }


    public Coupon getCouponsByNewB() {
        return couponDao.getCouponsByNewB();
    }

    public int updateCouponNum(Integer couponId) {

        return couponDao.updateCouponNum(couponId);
    }
    @Transactional
    public ModelMap createUserCoupon(int couponId) {
        Coupon coupon =couponDao.getCouponByCouponId(couponId);
        if(coupon==null){
            return  ReturnUtil.Error("不存在的优惠卷！");
        }
        if(coupon.getEndTime()!=null && coupon.getEndTime().before (new Date())){

            return  ReturnUtil.Error("优惠卷已过期！");
        }
        if(coupon.getStatus()==3){
            return  ReturnUtil.Error("已经生成过！");
        }
        List<UserCoupon> userCoupons = new ArrayList<>();
        for (int i = 0; i <coupon.getCouponNum() ; i++) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserCouponId(userCouponService.generateUserCouponId());
            //userCoupon.setUserId(userId);
            userCoupon.setCouponId(coupon.getCouponId());
            //添加用户使用次数的限制
            userCoupon.setUseNum(coupon.getUseNum());
            userCoupon.setCouponCode(CouponUtil.generateShortUuid());
            userCoupons.add(userCoupon);
        }

        if(userCoupons.size()>0){
           int rows = userCouponDao.addUserCouponByList(userCoupons);
            if(rows>0){
                Coupon couponUpdate = new Coupon();
                couponUpdate.setStatus(3);
                couponUpdate.setCouponId(couponId);
                couponDao.updateCoupon(couponUpdate);
                return  ReturnUtil.Success("生成成功");
            }else{
                return  ReturnUtil.Error("生成失败");
            }
        }else{
            return  ReturnUtil.Error("生成失败");

        }
    }

    public String generateWxCode(Coupon coupon) {
        String fileName = "coupon_wxCode_" + System.currentTimeMillis() +"_"+coupon.getCouponId() + ".jpeg";
        String wxCodeUrl = this.wxService.getWxACodeFromWx("c=" + coupon.getCouponId()+"&t=1", fileName, "pages/index/index");
        if (StringUtils.isNotBlank(wxCodeUrl)) {
            coupon.setWxCode(wxCodeUrl);
            int changeRow = this.couponDao.updateCouponCode(coupon);
            if (changeRow == 0) {
                logger.info(String.format("update machine wxCode fail, couponId = %s, wxCodeUrl = %s", coupon.getCouponId(), wxCodeUrl));
                return null;
            } else {
                return wxCodeUrl;
            }
        } else {
            return null;
        }
    }




    /**
     * 根据优惠卷id 返回优惠卷下的所有优惠卷
     * @param couponId,
     * @return
     */
    public ModelMap getCouponListById(int couponId,int Page,int PageSize) {
        List<UserCoupon> ls = userCouponDao.getAllCouponListById(couponId);
        return ReturnUtil.Success("查询成功",new Pagination<UserCoupon>(Page,PageSize,ls));
    }



    /**
     * 根据优惠卷id 返回优惠卷下的所有优惠卷
     * @param couponId,
     * @return
     */
    public List<UserCoupon> getCouponListById(int couponId) {
        return userCouponDao.getAllCouponListById(couponId);
    }
}
